package com.nike.main;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import cn.hellotrue.HelloTrue;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nike.bean.CustomName;
import com.nike.dao.NikeDao;
import com.nike.util.IPFactory;

public class NikeLoginForTelThreadMain extends Thread {
	// 版本
	public static String uncoming = "https://www.nike.com/cn/launch/?s=upcoming";
	public static String loginurl = "https://store.nike.com/cn/zh_cn/?l=shop,login_register";
	public static String addressurl = "https://www.nike.com/cn/zh_cn/p/settings";
	private Map<String, Object> zhanghaomap;
	private String ipAndPort;

	public String getIpAndPort() {
		return ipAndPort;
	}

	public void setIpAndPort(String ipAndPort) {
		this.ipAndPort = ipAndPort;
	}

	public Map<String, Object> getZhanghaomap() {
		return zhanghaomap;
	}

	public void setZhanghaomap(Map<String, Object> zhanghaomap) {
		this.zhanghaomap = zhanghaomap;
	}

	public NikeLoginForTelThreadMain(Map<String, Object> zhanghaomap, String ipAndPort) {
		super();
		this.zhanghaomap = zhanghaomap;
		this.ipAndPort = ipAndPort;
	}

	@Override
	public void run() {
		WebDriver wd = null;
		try {
			// 查询数据库，得到已发货的订单
			NikeDao dao = new NikeDao();
			System.setProperty("webdriver.chrome.driver",
					"c:\\chromedriver.exe");

//			ChromeOptions cop = new ChromeOptions();
//			Proxy proxy = new Proxy();
//			proxy.setHttpProxy(ipAndPort).setFtpProxy(ipAndPort)
//					.setSslProxy(ipAndPort);
//			cop.setProxy(proxy);
//			wd = new ChromeDriver(cop);
			wd = new ChromeDriver();
			String email = zhanghaomap.get("email") + "";
			String pwd = zhanghaomap.get("pwd") + "";
					
			wd.get(uncoming);
			
			wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
			//找登录按钮
			WebElement content = wd.findElement(By.className("content"));
				List<WebElement> alist = content.findElements(By
						.tagName("a"));
				if (alist != null && alist.size() > 0) {
					for (WebElement element : alist) {
						try{
							String text = element.getText();
							if (text != null && !"".equals(text)
									&& text.contains("登录")) {
								Thread.sleep(500);
								element.click();
								break;
							}
						}catch(Exception e){
							continue;
						}
					}
				}
				Thread.sleep(500);
				WebDriverWait wait = new WebDriverWait(wd, 10);
				wait.until(new ExpectedCondition<WebElement>() {
					@Override
					public WebElement apply(WebDriver d) {
						return d.findElement(By.id("nike-unite-loginForm"));
					}
				});
				if (wd.getPageSource().contains("登录NIKE⁠+账号")) {
					WebElement loginForm = wd.findElement(By
							.id("nike-unite-loginForm"));
					WebElement emailAddress = loginForm.findElement(By
							.name("emailAddress"));
					emailAddress.sendKeys(email);
					Thread.sleep(500);
					WebElement password = loginForm
							.findElement(By.name("password"));
					password.sendKeys("Q" + pwd);
					Thread.sleep(500);

					List<WebElement> inputlist = loginForm.findElements(By
							.tagName("input"));
					if (inputlist != null && inputlist.size() > 0) {
						for (WebElement element : inputlist) {
							String text = element.getAttribute("value");
							if (text != null && !"".equals(text)
									&& text.contains("登录")) {
								Thread.sleep(500);
								element.click();
								break;
							}
						}
					}
					Thread.sleep(500);
				//我的账户
				while(true){
					try{
						wd.switchTo().defaultContent();
						if (wd.getPageSource().contains("验证你的手机号码")){
							System.out.println("验证你的手机号码");
							break;
						}else if(wd.getPageSource().contains("重试")||wd.getPageSource().contains("错误")){
							System.out.println("重试");
							WebElement error = wd.findElement(By.id("nike-unite-error-view"));
							List<WebElement> inputlist2 = error.findElements(By.tagName("input"));
							if(inputlist2!=null && inputlist2.size()>0){
								for(WebElement element : inputlist2){
									String text = element.getAttribute("value");
									if(text!=null && !"".equals(text) && (text.contains("重试")||text.contains("错误"))){
										Thread.sleep(500);
										element.click();
										break;
									}
								}
							}
						}else if(wd.getPageSource().contains("登录")){
							inputlist = wd.findElements(By
									.tagName("input"));
							if (inputlist != null && inputlist.size() > 0) {
								for (WebElement element : inputlist) {
									String text = element.getAttribute("value");
									if (text != null && !"".equals(text)
											&& text.contains("登录")) {
										Thread.sleep(500);
										element.click();
										break;
									}
								}
							}
						}
					}catch(Exception e){
						continue;
					}
				}
				wd.switchTo().defaultContent();
				if (wd.getPageSource().contains("验证你的手机号码")) {
					//获取手机号。填入页面
					
					HelloTrue ht = new HelloTrue();
					 String httoken = HelloTrue.TOKEN;
						String telphone = ht.getPhone_nike(httoken);
						System.out.println(telphone);
					 WebElement progressiveForm = wd.findElement(By.id("nike-unite-progressiveForm"));
					 WebElement verifyMobileNumber = progressiveForm.findElement(By.name("verifyMobileNumber"));
					 verifyMobileNumber.sendKeys(telphone);//输入手机号
					 //点击发送验证码
					 List<WebElement> inputlist2 = progressiveForm.findElements(By.tagName("input"));
					if(inputlist2!=null && inputlist2.size()>0){
						for(WebElement element : inputlist2){
							String text = element.getAttribute("value");
							if(text!=null && !"".equals(text) && (text.contains("发送验证码"))){
								Thread.sleep(500);
								element.click();
								break;
							}
						}
					}
					wd.switchTo().defaultContent();
					if (wd.getPageSource().contains("输入你的验证码")) {
					//输入你的验证码
						
						 WebElement verifyCodeForm = wd.findElement(By.id("nike-unite-verifyCodeForm"));
						 WebElement code = verifyCodeForm.findElement(By.name("code"));
						 
							String telCode = ht.getMessage_nike(httoken, telphone);
							System.out.println("获取到的验证码信息为：" + telCode);
							if("超时".equals(telCode)){
								try {
									throw new Exception("未获取到验证码");
								} catch (Exception e) {
								}
							}
							String regEx="[^0-9]";   
							Pattern p = Pattern.compile(regEx);   
							telCode = p.matcher(telCode).replaceAll("").trim().substring(0,6);
							System.out.println("截取后的验证码信息为：" + telCode);
							code.sendKeys(telCode); //输入验证码
						
						//提交
						 List<WebElement> inputlist3 = verifyCodeForm.findElements(By.tagName("input"));
							if(inputlist3!=null && inputlist3.size()>0){
								for(WebElement element : inputlist3){
									String text = element.getAttribute("value");
									if(text!=null && !"".equals(text) && (text.contains("提交"))){
										Thread.sleep(500);
										element.click();
										break;
									}
								}
							} 
//							确定手机验证成功
							
							 zhanghaomap.put("tel",telphone);
//							 zhanghaomap.put("province","CN-34");
//							 zhanghaomap.put("city","7970");
//							 zhanghaomap.put("area","13663");
//							 zhanghaomap.put("address","安徽省滁州市来安县"+address);
							 dao.updateTelphone(zhanghaomap);
							//验证成功
//					String address = "汊河镇" + CustomName.getRoad() + "路"
//							+ CustomName.getNum() + "号" + CustomName.getNum() + "室";
//					wd.get(addressurl);
//					//点击地址
//					//等待地址刷新出来
//					
//					wait.until(new ExpectedCondition<WebElement>() {
//						@Override
//						public WebElement apply(WebDriver d) {
//							return d.findElement(By.className("edf-title-font-size--xsmall"));
//						}
//					}).isEnabled();
//					Thread.sleep(2000);
//					List<WebElement> lilist = wd.findElements(By.tagName("li"));
//					if (lilist != null && lilist.size() > 0) {
//						for (WebElement element : lilist) {
//							String text = element.getAttribute("data-content");
//							if (text != null && !"".equals(text)
//									&& text.contains(".addresses-content")) {
//								Thread.sleep(500);
//								try{
//									element.click();
//								}catch(Exception e){
//									Thread.sleep(2000);
//									element.click();
//								}
//								break;
//							}
//						}
//					}
//					Thread.sleep(1000);
//					//点击添加
//					
//					wait.until(new ExpectedCondition<WebElement>() {
//						@Override
//						public WebElement apply(WebDriver d) {
//							return d.findElement(By.className("address-list"));
//						}
//					}).isEnabled();
//					Thread.sleep(2000);
//					List<WebElement> buttonlist = wd.findElements(By.tagName("button"));
//					if (buttonlist != null && buttonlist.size() > 0) {
//						for (WebElement element : buttonlist) {
//							String text = element.getAttribute("data-type");
//							if (text != null && !"".equals(text)
//									&& text.contains("shipping")) {
//								Thread.sleep(500);
//								element.click();
//								break;
//							}
//						}
//					}
//					Thread.sleep(1000);
//					//address-form
//					wd.switchTo().defaultContent();
//					 WebElement lastNameAddr = wd.findElement(By.id("address-lastname"));
//					 lastNameAddr.sendKeys(lastname);
//					 Thread.sleep(500);
//					 WebElement firstNameAddr = wd.findElement(By.id("address-firstname"));
//					 firstNameAddr.sendKeys(firstname);
//					 Thread.sleep(500);
////					 String s11="document.getElementsByName('state')[0].value='CN-34';";//安徽省
////					 String s22="document.getElementsByName('city')[0].value='7970';";//滁州市
////					 String s33="document.getElementsByName('district')[0].value='13663'";//来安县
////					 JavascriptExecutor jse = (JavascriptExecutor)wd;
////					 jse.executeScript(s11);
////					 Thread.sleep(500);
////					 jse.executeScript(s22);
////					 Thread.sleep(500);
////					 jse.executeScript(s33);
////					 Thread.sleep(500);
//					 WebElement region_container = wd.findElement(By.className("region-container"));
//					 
//					 List<WebElement> divlist1 =  region_container.findElements(By.tagName("div"));
//					 if (divlist1 != null && divlist1.size() > 0) {
//							for (WebElement divelement : divlist1) {
//								try{
//									String css = divelement.getAttribute("class");
//									Thread.sleep(1000);
//									if(css.contains("country-state-container")){
//										List<WebElement> divlistitem1 = divelement.findElements(By.tagName("div"));
//										if (divlistitem1 != null && divlistitem1.size() > 0) {
//											for (WebElement elementitem : divlistitem1) {
//												String cssitem = elementitem.getAttribute("class");
//												if(cssitem.contains("container2")){
//													elementitem.findElement(By.tagName("a")).click();
//													Thread.sleep(1000);
//													//找ul下面的li
//													WebElement ul = elementitem.findElement(By.tagName("ul"));
//													List<WebElement> lilist1 = ul.findElements(By.tagName("li"));
//													if (lilist1 != null && lilist1.size() > 0) {
//														for (WebElement lielement : lilist1) {
//															try{
//																String text = lielement.getText();
//																if (text != null && !"".equals(text) && text.contains("安徽")) {
//																	Thread.sleep(500);
//																	lielement.click();
//																	break;
//																}
//															}catch(Exception e){
//																continue;
//															}
//														}
//													}
//												}
//											}
//										}
//									}else if(css.contains("city-district-container")){
//										List<WebElement> divlistitem1 = divelement.findElements(By.tagName("div"));
//										if (divlistitem1 != null && divlistitem1.size() > 0) {
//											for (WebElement divelementitem : divlistitem1) {
//												String cssitem = divelementitem.getAttribute("class");
//												Thread.sleep(1000);
//												if(cssitem.contains("container1")){
//													divelementitem.findElement(By.tagName("a")).click();
//													Thread.sleep(2000);
//													WebElement ul = divelementitem.findElement(By.tagName("ul"));
//													List<WebElement> lilist2 = ul.findElements(By.tagName("li"));
//													if (lilist2 != null && lilist2.size() > 0) {
//														for (WebElement lielement : lilist2) {
//															try{
//																String text = lielement.getText();
//																if (text != null && !"".equals(text) && text.contains("滁州")) {
//																	Thread.sleep(500);
//																	lielement.click();
//																	break;
//																}
//															}catch(Exception e){
//																continue;
//															}
//														}
//													}
//												}else if(cssitem.contains("container2")){
//													divelementitem.findElement(By.tagName("a")).click();
//													Thread.sleep(2000);
//													WebElement ul = divelementitem.findElement(By.tagName("ul"));
//													List<WebElement> lilist3 = ul.findElements(By.tagName("li"));
//													if (lilist3 != null && lilist3.size() > 0) {
//														for (WebElement lielement : lilist3) {
//															try{
//																String text = lielement.getText();
//																if (text != null && !"".equals(text) && text.contains("来安")) {
//																	Thread.sleep(500);
//																	lielement.click();
//																	break;
//																}
//															}catch(Exception e){
//																continue;
//															}
//														}
//													}
//												}
//											}
//										}
//									}
//								}catch(Exception e){
//									continue;
//								}
//							}
//						}
//					
//					
//					
//					 WebElement address1 = wd.findElement(By.id("address-addressone"));
//					 address1.sendKeys(address);
//					 Thread.sleep(500);
//					 System.out.println("填写邮编");
//					 WebElement postal_wrapper = wd.findElement(By.className("postal-wrapper"));
//					 WebElement postalCode = postal_wrapper.findElement(By.id("postalCode"));
//					 postalCode.sendKeys("669660");
//					 Thread.sleep(500);
//					 System.out.println("填写邮编结束");
////					 HelloTrue ht = new HelloTrue();
////					 String httoken = HelloTrue.TOKEN;
////					 String telphone = ht.getPhone_nike(httoken);
////					 System.out.println(telphone);
////					 WebElement phoneNumber = wd.findElement(By.id("address-phonenumber"));
////					 phoneNumber.sendKeys(telphone);
//					 Thread.sleep(500);
//					 List<WebElement> buttonlist2 = wd.findElements(By.tagName("button"));
//					 if(buttonlist2!=null && buttonlist2.size()>0){
//						 for(WebElement element : buttonlist2){
//							 String text = element.getText();
//							 if(text!=null && !"".equals(text) && text.contains("保存")){
//								 element.click();
//								 Thread.sleep(5000);
//								 //修改数据库相关字段
////								 zhanghaomap.put("tel",telphone);
//								 zhanghaomap.put("province","CN-34");
//								 zhanghaomap.put("city","7970");
//								 zhanghaomap.put("area","13663");
//								 zhanghaomap.put("address","安徽省滁州市来安县"+address);
//								 dao.updateLoginStatus(zhanghaomap);
//								 break;
//							 }
//						 }
					 }
					 //确定保存成功
				}
			}
			
			// 等待地址添加成功

			// 购买的时候查找 <a> 文字为购买的点击

			// 找li data-size="44" 的点击

			// 找<a> 内容为保存并继续的进行点击

			// 找<a> 内容为提交订单的进行点击

			// 等20秒 ,或者h3 等待付款，或者 前去付款

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// if (wd != null)
			// wd.close();
		}
	}

	public static void exeCmd(String commandStr) {
		// BufferedReader br = null;
		try {
			Runtime.getRuntime().exec(commandStr);
			// br = new BufferedReader(new
			// InputStreamReader(p.getInputStream()));
			// String line = null;
			// StringBuilder sb = new StringBuilder();
			// while ((line = br.readLine()) != null) {
			// sb.append(line + "\n");
			// }
			// System.out.println(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		// finally
		// {
		// if (br != null)
		// {
		// try {
		// br.close();
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// }
		// }
	}

	public static void main(String[] args) throws Exception {
		while (true) {
			// 杀掉所有进程,重新启动
			exeCmd("taskkill /F /im chromedriver.exe");
			Thread.sleep(2000);
			exeCmd("taskkill /F /im chrome.exe");
			Thread.sleep(2000);
			// 重启进程
			NikeDao dao = new NikeDao();
			List<Map<String, Object>> list = dao.getAllZhanghaoLoginForTel();
//			JSONObject jObject = IPFactory
//					.getKdByUrl(IPFactory.ZM_IP_HTTPS_URL_200);
//			JSONArray jArray = jObject.getJSONArray("proxy");
			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					Map<String, Object> zhanghaomap = list.get(i);
//					JSONObject jj = (JSONObject) jArray.get(i);
//					String ipAndPort = jj.getString("ip") + ":"
//							+ jj.getString("port");
					String ipAndPort =  IPFactory.getIpByQuanWang();
					NikeLoginForTelThreadMain xt = new NikeLoginForTelThreadMain(
							zhanghaomap, ipAndPort);
					xt.start();
				}
			}
			Thread.sleep(120000);
		}
	}
}
